<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <!-- 品牌 -->
    <div class="item">
      <div class="head">品牌：</div>
      <div class="body">
        <a
          href="javascript:;"
          v-for="brand in subCate.brands"
          :key="brand.id"
          :class="{ active: brand.selected === true }"
          @click="selectBrand(brand)"
        >
          {{ brand.name }}
        </a>
      </div>
    </div>
    <!-- 商品属性 -->
    <div class="item" v-for="prop in subCate.saleProperties" :key="prop.id">
      <div class="head">{{ prop.name }}：</div>
      <div class="body">
        <a
          href="javascript:;"
          v-for="item in prop.properties"
          :key="item.id"
          :class="{ active: item.selected === true }"
          @click="selectAttr(prop, item)"
        >
          {{ item.name }}
        </a>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'SubFilter',
  props: {
    subCate: {
      type: Object,
      default: () => ({})
    }
  },
  setup (props, { emit }) {
    // 收集目前参数
    const getFilter = () => {
      const params = {
        brandId: null,
        attrs: []
      }
      // 更新brandId
      // 找到selected为true的一项
      const brand = props.subCate.brands.find(it => it.selected)
      // 找得到是它，找不到是null
      params.brandId = brand ? brand.id : null

      // 更新attrs
      props.subCate.saleProperties.forEach(item => {
        const groupName = item.name
        const propertyName = item.properties.find(it => it.selected).name
        // 返回一个对象，根据接口文档定下来的结果
        if (propertyName && propertyName !== '全部') {
          return params.attrs.push(
            {
              groupName,
              propertyName
            })
        }
      })
      if (params.attrs.length === 0) { params.attrs = [] }
      return params
    }

    // 点击当前选项
    const selectBrand = (brand) => {
      // 1.更新品牌数据
      // 排他（干掉所有人包括自己）
      props.subCate.brands.forEach(it => { it.selected = false })
      // 选中自己
      brand.selected = true

      // 2.收集目前的参数，通知父组件重做查询
      emit('filter-change', getFilter())
    }

    const selectAttr = (prop, item) => {
      prop.properties.forEach(it => {
        it.selected = false
      })
      item.selected = true
      // 收集目前的参数，通知父组件重做查询
      emit('filter-change', getFilter())
    }
    return { selectBrand, selectAttr }
  }
}
</script>
<style scoped lang='less'>
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
